//
//  HomeMarryViewController.m
//  YiXiProject
//
//  Created by iMac on 2019/7/18.
//  Copyright © 2019 iMac. All rights reserved.
//

#import "HomeMarryViewController.h"

#import "HomeBottomView.h"                     // 页面底部view
#import "RegistViewController.h"               // 注册页面头文件
#import "SettingViewController.h"              // 设置 - 个人中心
#import "HomeTopView.h"                        // top视图
#import "CardViews.h"                          // Center

#import "FriendListViewController.h"           // 好友列表
#import "CurrentInforsViewController.h"        // 当前卡片详细信息
#import "MatchingSuccessView.h"                // 匹配成功提示


@interface HomeMarryViewController () <ClickButtonTagDelegate,TopBavBtnDelegate,MatchBtnBtnDelegate>

@property (nonatomic, strong) NSMutableArray *dataSources;
@property (nonatomic, strong) NSMutableArray *cards;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) CardViews *cardView;           // 页面中间view视图属性
@property (nonatomic, strong) HomeBottomView *bottomV;       // 页面底部view视图属性
@property (nonatomic, strong) HomeTopView *topView;          // 头部导航view
@property (nonatomic, strong) UIView *topCard;               //最上面
@property (nonatomic, strong) UIView *bottomCard;            //最底部
@property (nonatomic, assign) NSInteger isShuaXin;
@property (nonatomic, strong) NSString *type;
@property (nonatomic, assign) NSInteger clickCollect;


@property (nonatomic, strong) MatchingSuccessView *matView;  // 匹配成功提示

@property (nonatomic,strong) NSMutableArray *listArr;

@end

@implementation HomeMarryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    
    self.cards = [[NSMutableArray alloc] init];
    _dataSources = [NSMutableArray arrayWithObjects:@"image_1.jpg",@"image_2.jpg",@"image_3.jpg",@"image_3.jpg",nil];
    _listArr = [[NSMutableArray alloc]init];
    _page = 0;
    _isShuaXin = 0;
    _type = @"";
    _clickCollect = 0;
    
    [self reauestDatas];
    
    [self creatNavThreeItem];       // 页面头部item初始化
    
//    [self creatCardViewUI];         // 页面中间视图初始化
    
    [self creatBottomView];         // 页面底部视图初始化
    
    [self creatMatSuccessUI];       // 匹配成功提示
    
}

#pragma mark -- 获取数据
-(void)reauestDatas
{
    kWeakSelf(self);
    [HttpDatas requestHomeTOken:[YXUserdefaults GetDefaults:@"token"] page:_page pageSize:5 success:^(id  _Nonnull json) {
        
        NSLog(@"%@",[YXUserdefaults GetDefaults:@"token"]);
        
        // 数据类型判断
        if([json isKindOfClass:[NSDictionary class]])
        {
            // 是否请求成功（200则成功）
            if([json[@"status"]integerValue] == 200)
            {
                // 数据接收，实际开发中需要进行model处理
                weakself.listArr = json[@"data"];
                
                // 页面中间视图初始化
                [self creatCardViewUI];
            }
            else
            {
                // 问题提示
                [SVProgressHUD showSuccessWithStatus:json[@"message"]];
                [SVProgressHUD dismissWithDelay:SVPROGRESSHUDTIME];
            }
        }
        
    } failure:^(NSError * _Nonnull err) {
        printf("请求错误");
    }];
}

#pragma mark -- 1、收藏。2、喜欢。3、闪电
-(void)reauestThreeTypeDatas:(UIButton *)butt
{
    CardViews *cardView = self.cards[0];
    
    kWeakSelf(self);
    [HttpDatas requestHomeToken:[YXUserdefaults GetDefaults:@"token"] user_id:_listArr[cardView.tag-100][@"id"] type:_type success:^(id  _Nonnull json) {
        
        if([json isKindOfClass:[NSDictionary class]])
        {
            if([json[@"status"]integerValue] == 200)
            {
                if([weakself.type isEqualToString:@"1"] || [weakself.type isEqualToString:@"3"])
                {
                    [weakself cancelBtnClick:butt];
                }
                else if([weakself.type isEqualToString:@"2"])
                {
                    [weakself likeBtnClick:butt];
                }
                
                [SVProgressHUD showSuccessWithStatus:json[@"message"]];
                [SVProgressHUD dismissWithDelay:SVPROGRESSHUDTIME];
            }
            else
            {
                [SVProgressHUD showSuccessWithStatus:json[@"message"]];
                [SVProgressHUD dismissWithDelay:SVPROGRESSHUDTIME];
            }
        }
        
    } failure:^(NSError * _Nonnull err) {
        [SVProgressHUD showSuccessWithStatus:@"操作失败，稍后再试"];
        [SVProgressHUD dismissWithDelay:SVPROGRESSHUDTIME];
    }];
}

#pragma mark -- 创建也页面头部item
-(void)creatNavThreeItem
{
    _topView = [[HomeTopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, navCurentHeight+40)];
    _topView.delegate = self;
    [self.view addSubview:_topView];
}

// 创建页卡
-(void)creatCardViewUI
{
    for (int i = 0; i < _listArr.count; i++)
    {
        _cardView = [[CardViews alloc] initWithFrame:CGRectMake(0, 0, ImageWidth, ImageHeight)];
        _cardView.tag = 100 + i;

        int index = i;
        if (index == _listArr.count-1)
        {
            index = 1;
        }
        
        _cardView.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2+heightCard);
        
        _cardView.transform = CGAffineTransformMakeScale(1-ImageScale*index, 1-ImageScale*index);
        _cardView.currentImg.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];

        [_cardView installHomeDicDatas:_listArr[i]];
        //[_cardView installHomeArrData:_dataSources[i]];

        _cardView.infoButton.tag = _cardView.tag;
        [_cardView.infoButton addTarget:self action:@selector(clickInfo:) forControlEvents:UIControlEventTouchUpInside];

        [self.cards addObject:_cardView];

        [self.view addSubview:_cardView];
        [self.view sendSubviewToBack:_cardView];

        //添加拖动手势
        UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panHandle:)];
        [_cardView addGestureRecognizer:pan];

        _cardView.userInteractionEnabled = NO;
        if (i == 0) {
            _cardView.userInteractionEnabled = YES;
            self.topCard = _cardView;
        }else if (i == 3){
//            self.bottomCard = _cardView;
        }

    }
}

#pragma mark -- TopBavBtnDelegate
-(void)clickBtnTag:(NSInteger)tag
{
    switch (tag) {
        case 100:
            [self clickLeftItem];
            break;
        case 101:
            [self clickRightItem];
            break;
            
        default:
            break;
    }
}

#pragma mark -- 点击导航左侧item
-(void)clickLeftItem
{
    NSLog(@"我是左");
    
    UINavigationController *navSet = [[UINavigationController alloc]initWithRootViewController:[SettingViewController new]];
    
    [self presentViewController:navSet animated:YES completion:nil];
    
}

#pragma mark -- 点击导航右侧item
-(void)clickRightItem
{
    NSLog(@"我是右");
    
    FriendListViewController *frientVC = [[FriendListViewController alloc]init];
    
    [self.navigationController pushViewController:frientVC animated:YES];
}


#pragma maek -- 初始化页面底部视图
-(void)creatBottomView
{
    float heightV;
    if(navCurentHeight == 64)
    {
        heightV = 149.0;
    }
    else
    {
        heightV = 183.0;
    }
    
    self.bottomV = [[HomeBottomView alloc]initWithFrame:CGRectZero];
    self.bottomV.delegate = self;
    [self.view addSubview:self.bottomV];
    self.bottomV.sd_layout.leftSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).bottomSpaceToView(self.view, 0).heightIs(100);
}
#pragma mark -- MatchBtnBtnDelegate
-(void)clickTagNum:(UIButton *)tagNum
{
    switch (tagNum.tag) {
        case 100:
            NSLog(@"刷新");
            _isShuaXin = 1;
            [self cardresfresh];
            break;
            
        case 101:
            [self cancelBtnClick:tagNum];
            break;
            
        case 102:
            NSLog(@"收藏");
            _clickCollect = 1;
            _type = @"1";
            [self reauestThreeTypeDatas:tagNum];
            break;
            
        case 103:
            _type = @"2";
            [self reauestThreeTypeDatas:tagNum];
            break;
            
        case 104:
            NSLog(@"闪电");
            _type = @"3";
            [self reauestThreeTypeDatas:tagNum];
            
//            self.matView.hidden = NO;
//
//            if(self.matView.hidden == NO)
//            {
//                [UIView animateWithDuration:0.25 animations:^{
//
//                    self.matView.speakBtn.frame = CGRectMake(50, SCREEN_HEIGHT/2+80, SCREEN_WIDTH-100, 50);
//                    self.matView.sweepBtn.frame = CGRectMake(50, SCREEN_HEIGHT/2+160, SCREEN_WIDTH-100, 50);
//
//                }];
//            }
//            else
//            {
//                [UIView animateWithDuration:0.25 animations:^{
//
//                    self.matView.speakBtn.frame = CGRectMake(-SCREEN_WIDTH, SCREEN_HEIGHT/2+80, SCREEN_WIDTH-100, 50);
//                    self.matView.sweepBtn.frame = CGRectMake(SCREEN_WIDTH, SCREEN_HEIGHT/2+160, SCREEN_WIDTH-100, 50);
//
//                }];
//            }
            break;
            
        default:
            break;
    }
    
}

#pragma mark -- 匹配成功提示view
-(void)creatMatSuccessUI
{
    self.matView = [[MatchingSuccessView alloc]initWithFrame:self.view.bounds];
    self.matView.backgroundColor = ColorAlphe(28,30,43, 0.99);
    self.matView.hidden = YES;
    self.matView.delegate = self;
    [self.view addSubview:self.matView];
}
#pragma mark -- MatchBtnBtnDelegate
-(void)matchClickBtnTag:(NSInteger)tag
{
    switch (tag) {
        case 100:
            NSLog(@"speak");
            [self isHidderMatch];
            break;
            
        case 101:
            NSLog(@"sweep");
            [self isHidderMatch];
            break;
            
        default:
            break;
    }
}

// 隐藏提示view
-(void)isHidderMatch
{
    self.matView.hidden = YES;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self.matView.speakBtn.frame = CGRectMake(-SCREEN_WIDTH, SCREEN_HEIGHT/2+80, SCREEN_WIDTH-100, 50);
        self.matView.sweepBtn.frame = CGRectMake(SCREEN_WIDTH, SCREEN_HEIGHT/2+160, SCREEN_WIDTH-100, 50);
        
    }];
}
// 拖动方向
-(void)panHandle:(UIPanGestureRecognizer *)pan
{
    
    CardViews *cardView = (CardViews *)pan.view;
        
    if (pan.state == UIGestureRecognizerStateBegan) { //开始拖动
        
    }else if (pan.state == UIGestureRecognizerStateChanged) { //正在拖动
        
        CGPoint transLcation = [pan translationInView:cardView];
        cardView.center = CGPointMake(cardView.center.x + transLcation.x, cardView.center.y + transLcation.y);
        CGFloat XOffPercent = (cardView.center.x-SCREEN_WIDTH/2.0)/(SCREEN_WIDTH/2.0);
        CGFloat rotation = M_PI_2/4*XOffPercent;
        cardView.transform = CGAffineTransformMakeRotation(rotation);
        [pan setTranslation:CGPointZero inView:cardView];
        
        
        //视图在屏幕左侧移除
        if (cardView.frame.origin.x < 15)
        {
            cardView.disLikeImg.alpha = 1;
            cardView.likeImg.alpha = 0;
        }
        else //视图在屏幕右侧移除
        {
            cardView.disLikeImg.alpha = 0;
            cardView.likeImg.alpha = 1;
        }
        
        [self animationBlowViewWithXOffPercent:fabs(XOffPercent)];
        
        
    }else if (pan.state == UIGestureRecognizerStateEnded) { //松手了，拖动结束
        
        //视图不移除，原路返回
        if (cardView.center.x > 60 && cardView.center.x < SCREEN_WIDTH - 60) {
            [UIView animateWithDuration:0.25 animations:^{
                cardView.center = CGPointMake(SCREEN_WIDTH/2.0, SCREEN_HEIGHT/2.0+heightCard);
                cardView.transform = CGAffineTransformMakeRotation(0);
                [self animationBlowViewWithXOffPercent:0];
            }];
            
        }else{
            
            //视图在屏幕左侧移除
            if (cardView.center.x < 60) {
                [UIView animateWithDuration:0.25 animations:^{
                    cardView.center = CGPointMake(-200, cardView.center.y+20);
                }];
                
            } else{//视图在屏幕右侧移除
                [UIView animateWithDuration:0.25 animations:^{
                    cardView.center = CGPointMake(SCREEN_WIDTH+200, cardView.center.y+20);
                }];
            }
            
            [self animationBlowViewWithXOffPercent:1];
            [self performSelector:@selector(cardRemove) withObject:cardView afterDelay:0.25];
        }
        
        cardView.disLikeImg.alpha = 0;
        cardView.likeImg.alpha = 0;
    }
    
}

// 移动最上层card时后面的card缩放动画
- (void)animationBlowViewWithXOffPercent:(CGFloat)XOffPercent {
    
    for (UIView *card in self.cards) {
        
        if (card != self.topCard && card.tag != _listArr.count-1) {
            
            NSInteger index = card.tag-100;
            
            card.center = CGPointMake(SCREEN_WIDTH/2,SCREEN_HEIGHT/2+heightCard);
            
            CGFloat scale = 1-ImageScale*index + XOffPercent*ImageScale;
            card.transform = CGAffineTransformMakeScale(scale, scale);
        }
    }
    
}
// 手势拖动移除
-(void)cardRemove
{
    //    滑动结束第一张和放到数组最后
    [self.cards removeObject:self.topCard];
    //[self.cards addObject:self.topCard];
    
    //    重新设置tag
    for (int i = 0 ; i < _cards.count; i++) {
        UIView *card = self.cards[i];
        card.tag = 100+i;
    }
    
    //    重置第一张和最后一张（第4）
    self.topCard.userInteractionEnabled = NO;
    self.topCard.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2+heightCard);
    self.topCard.transform = CGAffineTransformMakeScale(1-ImageScale*2, 1-ImageScale*2);
//    [self.view sendSubviewToBack:self.topCard];
    [self.topCard removeFromSuperview];
    
//    self.bottomCard = self.topCard;
    
    UIView *currentCard = self.cards.firstObject;
    currentCard.userInteractionEnabled = YES;
    self.topCard = currentCard;
    
    if(_cards.count == 0)
    {
        _page += 1;
        [self reauestDatas];
    }
}

// 刷新
-(void)cardresfresh
{
    for (int i = 0; i < _cards.count; i ++)
    {
        CardViews *cardView = _cards[i];
        [cardView removeFromSuperview];
    }
    
    [_cards removeAllObjects];
    _page += 1;
    
    [self reauestDatas];
}

#pragma mark -- 当前页卡信息按钮
-(void)clickInfo:(UIButton *)sender
{
    NSLog(@"%ld",sender.tag);
    
    CurrentInforsViewController *curInfoVC = [[CurrentInforsViewController alloc]init];
    curInfoVC.user_id = _listArr[sender.tag-100][@"id"];
    curInfoVC.imgStr = _listArr[sender.tag-100][@"photo"];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:curInfoVC];
    [self presentViewController:nav animated:YES completion:nil];
}

//不喜欢
- (void)cancelBtnClick:(UIButton *)sender
{
    // 显示不喜欢
    CardViews *cardView = self.cards[0];
    
    cardView.likeImg.alpha = 0;
    cardView.disLikeImg.alpha = 1;
    
    if(_clickCollect == 1)
    {
        cardView.disLikeImg.text = @"收藏";
    }
    else
    {
        cardView.disLikeImg.text = @"Like";
    }
    
    
    [UIView animateWithDuration:0.5 animations:^{
        
        sender.enabled = NO;
        
        self.topCard.center = CGPointMake(-ImageWidth, SCREEN_HEIGHT/2+heightCard);
        self.topCard.transform = CGAffineTransformMakeRotation(-M_PI_4/2);
        
        for (UIView *card in self.cards)
        {
            if (card.tag != 100 && card.tag != self.listArr.count-1)
            {
                NSInteger index = card.tag - 100;
                
                card.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2+heightCard);
                
                CGFloat scale = 1-index*ImageScale + ImageScale;
                card.transform = CGAffineTransformMakeScale(scale, scale);
            }
        }
        
    }completion:^(BOOL finished) {
        
        cardView.likeImg.alpha = 0;
        cardView.disLikeImg.alpha = 0;
        
        self.clickCollect = 0;
        
        sender.enabled = YES;
        [self cardRemove];
    }];
}

//喜欢
- (void)likeBtnClick:(UIButton *)sender
{
    
    // 显示喜欢
    CardViews *cardView = self.cards[0];
    
    cardView.likeImg.alpha = 1;
    cardView.disLikeImg.alpha = 0;
    
    [UIView animateWithDuration:0.5 animations:^{
        
        sender.enabled = NO;
        
        self.topCard.center = CGPointMake(ImageWidth+ImageWidth, SCREEN_HEIGHT/2+heightCard);
        self.topCard.transform = CGAffineTransformMakeRotation(M_PI_4/2);
        
        for (UIView *card in self.cards)
        {
            if (card.tag != 100 && card.tag != self.listArr.count-1)
            {
                NSInteger index = card.tag - 100;
                
                card.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2+heightCard);
                
                CGFloat scale = 1-index*ImageScale + ImageScale;
                card.transform = CGAffineTransformMakeScale(scale, scale);
            }
        }
        
    }completion:^(BOOL finished) {
        
        cardView.likeImg.alpha = 0;
        cardView.disLikeImg.alpha = 0;
        
        sender.enabled = YES;
        
        [self cardRemove];
    }];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
